package com.ruoyi.project.qiChe.kongZhi.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.project.qiChe.kongZhi.domain.KongZhi;
import com.ruoyi.project.qiChe.kongZhi.mapper.KongZhiMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.project.system.role.domain.Role;

/**
 * 控制管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class KongZhiServiceImpl implements IKongZhiService
{
    @Autowired
    private KongZhiMapper kongZhiMapper;

    /**
     * 查询控制管理数据
     * 
     * @param dept 控制信息
     * @return 控制信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<KongZhi> selectDeptList(KongZhi dept)
    {
        return kongZhiMapper.selectDeptList(dept);
    }

    /**
     * 查询控制管理树
     * 
     * @param dept 控制信息
     * @return 所有控制信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(KongZhi dept)
    {
        List<KongZhi> deptList = kongZhiMapper.selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询控制管理树（排除下级）
     * 
     * @return 所有控制信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTreeExcludeChild(KongZhi dept)
    {
        Long deptId = dept.getDeptId();
        List<KongZhi> deptList = kongZhiMapper.selectDeptList(dept);
        Iterator<KongZhi> it = deptList.iterator();
        while (it.hasNext())
        {
            KongZhi d = (KongZhi) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询控制（数据权限）
     *
     * @param role 角色对象
     * @return 控制列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(Role role)
    {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<KongZhi> deptList = selectDeptList(new KongZhi());
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleDeptList = kongZhiMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        }
        else
        {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转控制树
     *
     * @param deptList 控制列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<KongZhi> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转控制树
     *
     * @param deptList 控制列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<KongZhi> deptList, List<String> roleDeptList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (KongZhi dept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询控制人数
     * 
     * @param parentId 控制ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId)
    {
        KongZhi dept = new KongZhi();
        dept.setParentId(parentId);
        return kongZhiMapper.selectDeptCount(dept);
    }

    /**
     * 查询控制是否存在用户
     * 
     * @param deptId 控制ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = kongZhiMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 删除控制管理信息
     * 
     * @param deptId 控制ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return kongZhiMapper.deleteDeptById(deptId);
    }

    /**
     * 新增保存控制信息
     * 
     * @param dept 控制信息
     * @return 结果
     */
    @Override
    public int insertDept(KongZhi dept)
    {
        KongZhi info = kongZhiMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("控制停用，不允许新增");
        }
        dept.setCreateBy(ShiroUtils.getLoginName());
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return kongZhiMapper.insertDept(dept);
    }

    /**
     * 修改保存控制信息
     * 
     * @param dept 控制信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(KongZhi dept)
    {
        KongZhi newParentDept = kongZhiMapper.selectDeptById(dept.getParentId());
        KongZhi oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        dept.setUpdateBy(ShiroUtils.getLoginName());
        int result = kongZhiMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该控制是启用状态，则启用该控制的所有上级控制
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该控制的父级控制状态
     * 
     * @param dept 当前控制
     */
    private void updateParentDeptStatus(KongZhi dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = kongZhiMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        kongZhiMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的控制ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<KongZhi> children = kongZhiMapper.selectChildrenDeptById(deptId);
        for (KongZhi child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            kongZhiMapper.updateDeptChildren(children);
        }
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 控制ID
     * @param ancestors 元素列表
     */
    public void updateDeptChildren(Long deptId, String ancestors)
    {
        KongZhi dept = new KongZhi();
        dept.setParentId(deptId);
        List<KongZhi> childrens = kongZhiMapper.selectDeptList(dept);
        for (KongZhi children : childrens)
        {
            children.setAncestors(ancestors + "," + dept.getParentId());
        }
        if (childrens.size() > 0)
        {
            kongZhiMapper.updateDeptChildren(childrens);
        }
    }

    /**
     * 根据控制ID查询信息
     * 
     * @param deptId 控制ID
     * @return 控制信息
     */
    @Override
    public KongZhi selectDeptById(Long deptId)
    {
        return kongZhiMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子控制（正常状态）
     * 
     * @param deptId 控制ID
     * @return 子控制数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return kongZhiMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验控制名称是否唯一
     * 
     * @param dept 控制信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(KongZhi dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        KongZhi info = kongZhiMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }
}
